<template>
	<!-- 2024_6_20 修改 -->
 <!-- <el-button type="primary" plain icon="Plus" @click="handleAddScore" v-show="props.auditStatus!=3"
    >新增</el-button
  > -->
  <!-- 修改后 -->
  <el-button type="primary" plain icon="Plus" @click="handleAddScore" v-show="props.auditStatus == 0"
    >新增</el-button
  >
  <!-- 添加隐藏  2024_6_20 修改-->
  <!-- <el-tooltip class="item" effect="dark" content="刷新" placement="top" >
    <el-button circle icon="Refresh" @click="update" />
  </el-tooltip> -->
  
  <el-tooltip class="item" effect="dark" content="刷新" placement="top" v-show="props.auditStatus == 0">
    <el-button circle icon="Refresh" @click="update" v-show="props.auditStatus == 0"/>
  </el-tooltip>
  
  <el-table
    :data="ScoreRuleList"
    border
    style="width: 95%; margin-top: 20px; border-radius: 8px;box-shadow: 5px 5px 10px rgba(64, 158, 255, 0.5);"
    :header-cell-style="{
      background: '#337ecc !important',
      color: '#ffffff',
      border: 'none !important',
    }"
    :span-method="(value) => rowSpanRulesHandler(value, ScoreRuleList)"
  >
  
  <el-table-column label="考核条目类型" width="200" >
    <template #default="scope">
          <div>{{ scope.row.type }}</div>
    </template>
  </el-table-column>
    <el-table-column label="考核条目" width="200" class-name="my-content">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>备注：{{ scope.row.ins }}</div>
          </template>
          <template #reference>{{ scope.row.target }}</template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column prop="percent" label="考核条目占比" width="120">
      <template #default="scope">
        <el-tag disable-transitions>{{ scope.row.scorePercent }}%</el-tag>
      </template>
    </el-table-column>
    <el-table-column
      prop="state"
      label="状态"
      width="80"
    >
      <template #default="scope">
        <el-tag
          :type="scope.row.tag === 'Home' ? '' : 'success'"
          disable-transitions
          >{{ scope.row.state === 0 ? "未启用" : "启用" }}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column prop="assessorName" label="考核人" width="150" />
    <el-table-column prop="assessorPercent" label="考核人占比" width="120">
      <template #default="scope">
        <el-tag disable-transitions>{{ scope.row.assessorPercent }}%</el-tag>
      </template>
    </el-table-column>
	
    <el-table-column prop="updateTime" label="最后更新时间" width="250" >
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-icon><timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
        </div>
      </template>
    </el-table-column>
	
    <el-table-column label="操作" v-show="props.auditStatus == 0">
      <template #default="scope" v-show="props.auditStatus == 0">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-show="props.auditStatus == 0">编辑</el-button>
        <el-button size="small" @click="handleDelete(scope.$index, scope.row)" v-show="props.auditStatus == 0" type="danger">删除</el-button>
      </template>
    </el-table-column>
	
  </el-table>
  <ScoreDialog
    v-model="ScoreDialogVisible"
    :fourthId="fourthId"
    :id="id"
    :close="close"
    :update="update"
    :type="type"
    :selectContent="selectContent"
    :dialogType="dialogType"
    :title="title"
  ></ScoreDialog>
  <UploadExcel
        v-model="upload.open"
        :title="upload.upLoadTitle"
        :url="importUrl"
        @onSuccess="onSuccess"
        @onDownTemplate="onDownTemplate"
      ></UploadExcel>
</template>
<script setup>
import { ref, onMounted, onBeforeMount, reactive, watch } from "vue";
import { getScoreRuleList } from "@/api/api";
import { getPositionScoreList, removeAssessor } from "@/api/score";
import ScoreDialog from "./ScoreDialog";
import { ElMessage } from "element-plus";
import UploadExcel from "@/components/UploadExcel/index";

let props = defineProps({
  id: {
    type: String,
    required: true, //是否规定必须得有
  },
  fourthId: {
    type: Number,
    required: true,
  },
  thirdId: {
    type: Number,
    required: true,
  },
  type: {
    type: Number,
    require: true,
  },
  auditStatus:{
    type: Number,
    require: true,
  },
  read:{
	  type:Boolean,
	  require:true,
  }
});

const id = ref({
  id: props.id,
});
const fourthId = ref({
  fourthId: Number(props.fourthId),
});

const ScoreRuleList = ref([]);
onBeforeMount(() => {
  let positionId = props.id;
  getPositionScoreList({ positionId }).then((data) => {
    ScoreRuleList.value = data.data;
  });
});
watch(
  ScoreRuleList,
  (newVal) => {
    
  },
  { deep: true }
);

const importUrl = ref('/Position/upload');
const upload = ref({
  open: false,
  upLoadTitle: "岗位评分条目上传",
});
const onSuccess = (res) => {
  if (res.code==200) {
    ElMessage.success('岗位评分条目上传成功');
    update()
  } else {
    router.push({
      path: '/account/error',
    });
    eventBus.on('showErrorExist', () => {
      eventBus.emit('showError', res.data);
    });
  }
  upload.value.open = false;
};
const handleUP = () => {
  upload.value.open = true;
};

const title = ref("添加评分条目");
const dialogType = ref("add");
const selectContent = ref([]);
const ScoreDialogVisible = ref(false);
const handleAddScore = (row) => {
  title.value = "添加评分条目";
  dialogType.value = "add";
  ScoreDialogVisible.value = true;
  selectContent.value = {
    id:"",
    scoreId: "",
    positionId: "",
    percent: "",
    state: true,
    ins: "",
  };
};
const handleEdit = (index, row) => {
  title.value = "编辑评分条目";
  dialogType.value = "edit";
  ScoreDialogVisible.value = true;
  selectContent.value = row;
};
const handleDelete = (index, row) => {
  removeAssessor(row).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      update();
    } else {
      ElMessage.error("删除失败");
    }
  });
};

const close= () => {
  ScoreDialogVisible.value = false;
};

const update = () => {
  let positionId = props.id;
  getPositionScoreList({ positionId }).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "更新成功",
        type: "success",
      });
      ScoreRuleList.value = data.data;
      
    } else {
      ElMessage.error("更新失败");
    }
  });
};

const compareSingleAttrReturnColSpan = (row, compareAttr, index, tableData) => {
  let count = 0;
    let start = index;
  
    
    while (start < tableData.length) {
    	
    		
    	if(start > index &&compareAttr==="scorePercent"&&row["target"] !== tableData[start]["target"]){
    		break
    	}else{
    		// 进入循环，检查下一个元素
    		if (start > index && row[compareAttr] !== tableData[start][compareAttr]) {
    			break;  // 如果不相等，则停止合并
    		}
    		count++;  // 计数相同的行
    		start++;  // 移动到下一行
    	}
    	
      
    }
  
    // 将合并的行数存储在行数据中
    if (start > index) {
      tableData[index][`${compareAttr}_count`] = count;
    }
  
    // 检查前一行的合并数量与当前行是否相等
    const previousRowCount = index > 0 ? tableData[index - 1][`${compareAttr}_count`] : 0;
    return previousRowCount === count + 1 ? [0, 0] : [count, 1];
};

const columns = [
  "type",
  "target",
  "scorePercent",
  "assessorName",
  "updateTime",
  "assessorPercent",
  "score",
  "grade",
  "remark"
];
const rowSpanRulesHandler = ({  row, column, rowIndex, columnIndex }, data) => {
  //console.log(columns[columnIndex]);
 // 根据列名判断进行合并
   if (columns[columnIndex] === "type") {
     return compareSingleAttrReturnColSpan(row, "type", rowIndex, data);
   } else if (columns[columnIndex] === "target") {
     return compareSingleAttrReturnColSpan(row, "target", rowIndex, data);
   } else if (columns[columnIndex] === "scorePercent") {
     return compareSingleAttrReturnColSpan(row, "scorePercent", rowIndex, data);
   }
};
</script>

<style lang="scss" scoped>
.title1 {
  color: #95d475;
  width: 200px;
  height: 45px;
  font-size: 25px;
  background: rgba(179, 225, 157, 0.4);
  text-align: center;
  border-radius: 10px;
  margin: 20px auto;
  line-height: 45px;
  border-top: #95d475 2px solid;
  border-bottom: #95d475 2px solid;
  box-shadow: 5px 5px 10px rgba(179, 225, 157, 0.5);
}
:deep(.my-content) {
  background: #ecf5ff !important;
  font-size: 15px;
}
</style>